<!--
 * @author  guojiteng
 设置填空题跳转
-->
<template>
  <div class="question-tiankong-jump">
    <el-form
      ref="tiankongform"
      :model="baseform"
      class="dataForm nomt"
      label-position="right"
      label-width="140px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="题干" prop="stem">
            <el-input
              v-model.trim="baseform.stem"
              disabled
              :rows="2"
              type="textarea"
              placeholder="题干这里填写题目描述"
            />
          </el-form-item>
        </el-col>
        <!--整数型填空和小数型填空-->
        <template v-if="type === 'WJWTLX_05' || type === 'WJWTLX_06'">
          <el-col :span="24">
            <el-form-item label="最小值">
              <el-col :span="8">
                <el-input-number v-if="type === 'WJWTLX_05'" v-model.trim="limitRange.minOption" style="width: 100%;" :precision="0" placeholder="请输入最小值" disabled controls-position="right" />
                <el-input-number v-else v-model.trim="limitRange.minOption" style="width: 100%;" placeholder="请输入最小值" disabled controls-position="right" />
              </el-col>
              <el-col :span="3" style="text-align: right;">
                <el-checkbox v-model="limitRange.optionFloor" disabled label="无限制">不限定</el-checkbox>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="最大值">
              <el-col :span="8">
                <el-input-number v-if="type === 'WJWTLX_05'" v-model.trim="limitRange.maxOption" disabled style="width: 100%;" :precision="0" placeholder="请输入最大值" controls-position="right" />
                <el-input-number v-else v-model.trim="limitRange.maxOption" disabled style="width: 100%;" placeholder="请输入最大值" controls-position="right" />
              </el-col>
              <el-col :span="3" style="text-align: right;">
                <el-checkbox v-model="limitRange.optionUpper" disabled label="无限制">不限定</el-checkbox>
              </el-col>
            </el-form-item>
          </el-col>
        </template>
        <!--日期型填空-->
        <template v-else-if="type === 'WJWTLX_07'">
          <el-col :span="24">
            <el-form-item label="最早日期">
              <el-col :span="8">
                <el-date-picker v-model="limitRange.minOption" disabled type="date" placeholder="选择开始日期" style="width: 100%;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
              </el-col>
              <el-col :span="3" style="text-align: right;">
                <el-checkbox v-model="limitRange.optionFloor" disabled label="无限制">不限定</el-checkbox>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="最晚日期">
              <el-col :span="8">
                <el-date-picker v-model="limitRange.maxOption" disabled type="date" placeholder="选择结束日期" style="width: 100%;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
              </el-col>
              <el-col :span="3" style="text-align: right;">
                <el-checkbox v-model="limitRange.optionUpper" disabled label="无限制">不限定</el-checkbox>
              </el-col>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <!--跳转题目配置 -->
    <template>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>跳转题目配置</span>
          <el-button style="float: right;" type="primary" @click="addJumpList">添加</el-button>
        </div>
        <div v-for="(item,i) in jumpList" :key="i" style="margin-bottom: 20px">
          <el-row>
            <el-col :span="10">
              <el-radio v-model="item.flag1" :disabled="item.flag1Check" label="gtr">大于</el-radio>
              <el-radio v-model="item.flag1" :disabled="item.flag1Check" label="gtreq">大于等于</el-radio>
              <el-date-picker v-if="type === 'WJWTLX_07'" v-model="item.value1" :disabled="item.flag1==='nolimit'" :picker-options="pickerOptions0" type="date" placeholder="选择开始日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
              <el-input-number v-else-if="type === 'WJWTLX_05'" v-model.trim="item.value1" :max="limitRange.optionUpper?Infinity:limitRange.maxOption" :min="limitRange.optionFloor?-Infinity:limitRange.minOption" :disabled="item.flag1==='nolimit'" :precision="0" placeholder="请输入整数" controls-position="right" />
              <el-input-number v-else v-model.trim="item.value1" :max="limitRange.optionUpper?Infinity:limitRange.maxOption" :min="limitRange.optionFloor?-Infinity:limitRange.minOption" :disabled="item.flag1==='nolimit'" placeholder="请输入小数" :precision="2" controls-position="right" />
              <el-checkbox v-model="item.flag1Check" @change="changeVal($event,1,i)">不限</el-checkbox>
            </el-col>
            <el-col :span="10">
              <el-radio v-model="item.flag2" :disabled="item.flag2Check" label="let">小于</el-radio>
              <el-radio v-model="item.flag2" :disabled="item.flag2Check" label="leteq">小于等于</el-radio>
              <el-date-picker v-if="type === 'WJWTLX_07'" v-model="item.value2" :disabled="item.flag2==='nolimit'" :picker-options="pickerOptions0" type="date" placeholder="选择开始日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
              <el-input-number v-else-if="type === 'WJWTLX_05'" v-model.trim="item.value2" :max="limitRange.optionUpper?Infinity:limitRange.maxOption" :min="limitRange.optionFloor?-Infinity:limitRange.minOption" :disabled="item.flag2==='nolimit'" :precision="0" placeholder="请输入整数" controls-position="right" />
              <el-input-number v-else v-model.trim="item.value2" :max="limitRange.optionUpper?Infinity:limitRange.maxOption" :min="limitRange.optionFloor?-Infinity:limitRange.minOption" :disabled="item.flag2==='nolimit'" placeholder="请输入小数" :precision="2" controls-position="right" />
              <el-checkbox v-model="item.flag2Check" @change="changeVal($event,2,i)">不限</el-checkbox>
            </el-col>
            <el-col :span="4">
              <el-select v-model="item.toid" style="width: 85%" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in qList"
                  :key="item.id"
                  :label="item.stem"
                  :value="item.id"
                />
              </el-select>
              <i class="el-icon-delete" @click="removeJump(i)" />
            </el-col>
          </el-row>
        </div>
      </el-card>
    </template>
  </div>
</template>
<script>
export default {
  name: 'Tiankong',
  props: {
    type: {
      type: String,
      default: '40'
    },
    getData: {
      type: Object,
      default: () => {
      }
    },
    qList: {
      type: Array,
      default: []
    }
  },
  data() {
    const ths = this
    return {
      baseform: {
        stem: ''
      },
      pickerOptions0: {
        disabledDate(time) {
          if (!ths.limitRange.optionFloor && !ths.limitRange.optionUpper) { // 同时设置
            return time.getTime() > new Date(ths.limitRange.maxOption).getTime() || time.getTime() < (new Date(ths.limitRange.minOption).getTime() - 24 * 3600 * 1000)
          } else if (!ths.limitRange.optionFloor) { // 设置了最早日期
            return time.getTime() < (new Date(ths.limitRange.minOption).getTime() - 24 * 3600 * 1000)
          } else if (!ths.limitRange.optionUpper) { // 设置了最晚日期
            return time.getTime() > new Date(ths.limitRange.maxOption).getTime()
          } else {
            console.log('两个不限制')
            return time.getTime() > new Date('2099-01-01')
          }
        }
      },
      jumpList: [],
      limitRange: {
        optionFloor: true,
        optionUpper: true,
        minOption: '',
        maxOption: ''
      },
      day: 86400000// 一天的毫秒数
    }
  },
  watch: {

  },
  created() {
    if (this.getData && this.getData.id) {
      try {
        this.$set(this.baseform, 'stem', this.getData.stem)
        if (this.getData.questionJson) {
          this.$set(this, 'limitRange', JSON.parse(this.getData.questionJson))
        }
        if (this.getData.questionSkip && this.getData.questionSkip !== '') {
          this.jumpList = JSON.parse(this.getData.questionSkip)
          if (this.jumpList.length === 0) {
            this.addJumpList()
          }
        } else {
          this.addJumpList()
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '参数异常，请重试!',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
    }
  },
  methods: {
    getMaxNum() {
      if (this.limitRange.optionUpper) { // 如果是不限制就返回无限大
        return Infinity
      } else {
        return this.limitRange.maxOption
      }
    },
    getMinNum() {
      if (this.limitRange.optionUpper) { // 如果是不限制就返回无限小
        return -Infinity
      } else {
        return this.limitRange.minOption
      }
    },
    getJson() {
      // 先把选择对应题目的选项删选出来
      const list = this.jumpList.filter(a => { return a.toid !== '' })
      if (list.length === 0) {
        return JSON.stringify([])
      }
      const newList = [...list]
      const lineList = []// 所有数据都在一条线上
      for (var i = 0; i < newList.length; i++) {
        const item = newList[i]
        let obj = { // 大于相关的数据
          line: i,
          num: item.value1
        }
        let obj2 = { // 小于相关的数据
          line: i,
          num: item.value2
        }
        if (item.flag1 === 'nolimit') {
          obj = this.setGtrNoLimit(obj)
        } else if (item.flag1 === 'gtr') {
          if (obj.num === '') {
            this.$message.error('大于相关的值不允许为空')
            return ''
          }
          obj = this.setGtr(obj)
        } else if (item.flag1 === 'gtreq') {
          if (obj.num === '') {
            this.$message.error('大于等于相关的值不允许为空')
            return ''
          }
          obj = this.setDefault(obj)
        }
        if (item.flag2 === 'nolimit') {
          obj2 = this.setLetNoLimit(obj2)
        } else if (item.flag2 === 'let') {
          if (obj2.num === '') {
            this.$message.error('小于相关的值不允许为空')
            return ''
          }
          obj2 = this.setLet(obj2)
        } else if (item.flag2 === 'leteq') {
          if (obj2.num === '') {
            this.$message.error('小于等于相关的值不允许为空')
            return ''
          }
          obj2 = this.setDefault(obj2)
        }
        if (obj.num > obj2.num) {
          this.$message.error('区间配置有误，请检查!')
          return ''
        }
        lineList.push(obj)
        lineList.push(obj2)
      }
      // 排序
      const sortList = lineList.sort(this.compare('num'))
      let success = true
      console.log('排序后的', sortList)
      for (var i = 0; i < sortList.length;) {
        if (i !== sortList.length - 1) {
          const u = sortList[i]
          const n = sortList[i + 1]
          if ((Number(u.num) < Number(n.num) && u.line === n.line) || (Number(u.num) === Number(n.num) && u.line === n.line)) {
            // 查询所有有这个值的对象
            const uall = sortList.filter(a => {
              return a.num === u.num
            })
            if (uall.length > 2) {
              this.$message.error('区间配置有误，请检查!')
              return ''
            } else {
              i = i + 2
            }
          } else {
            success = false
            this.$message.error('区间配置有误，请检查!')
            return ''
          }
        }
      }
      if (success) {
        const JSONlist = this.jumpList.filter(a => { return a.toid !== '' })
        if (JSONlist.length === 0) {
          return ''
        }
        return JSON.stringify(JSONlist)
      }
    },
    /**
     * 对数据进行排序
     * */
    compare(property) {
      return function(a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    /**
     * 设置默认的数据
      */
    setDefault(obj) {
      if (this.type === 'WJWTLX_07') { // 如果是日期格式
        obj.num = new Date(obj.num).getTime()
      } else if (this.type === 'WJWTLX_06' || this.type === 'WJWTLX_05') { // 小数型填空或者整数填空
        obj.num = Number(obj.num)
      }
      return obj
    },
    /**
     * 去设置大于不限的数据
     * */
    setGtrNoLimit(obj) {
      if (this.type === 'WJWTLX_07') { // 如果是日期格式
        obj.num = new Date('1900-01-01').getTime()
      } else if (this.type === 'WJWTLX_06') { // 小数型填空
        obj.num = -99999999.00
      } else if (this.type === 'WJWTLX_05') { // 整数型填空
        obj.num = -99999999
      }
      return obj
    },
    /**
     * 去设置小于不限的数据
     * */
    setLetNoLimit(obj) {
      if (this.type === 'WJWTLX_07') { // 如果是日期格式
        obj.num = new Date('2099-01-01').getTime()
      } else if (this.type === 'WJWTLX_06') { // 小数型填空
        obj.num = 99999999.00
      } else if (this.type === 'WJWTLX_05') { // 整数型填空
        obj.num = 99999999
      }
      return obj
    },
    /**
     * 设置大于的数据，如果是大于都设置为大于等于的值加1
     * */
    setGtr(obj) {
      if (this.type === 'WJWTLX_07') { // 如果是日期格式
        obj.num = new Date(obj.num).getTime() + this.day
      } else if (this.type === 'WJWTLX_06') { // 小数型填空
        obj.num = this.accAdd(obj.num, 0.01) // obj.num + 0.01
      } else if (this.type === 'WJWTLX_05') { // 整数型填空
        obj.num = obj.num + 1
      }
      return obj
    },
    accAdd(arg1, arg2) {
      var r1, r2, m
      try { r1 = arg1.toString().split('.')[1].length } catch (e) { r1 = 0 }
      try { r2 = arg2.toString().split('.')[1].length } catch (e) { r2 = 0 }
      m = Math.pow(10, Math.max(r1, r2))
      return Number((arg1 * m + arg2 * m) / m)
    },
    /**
     * 设置小于于的数据，如果是小于于都设置为小于等于的值减1
     * */
    setLet(obj) {
      if (this.type === 'WJWTLX_07') { // 如果是日期格式
        obj.num = new Date(obj.num).getTime() - this.day
      } else if (this.type === 'WJWTLX_06') { // 小数型填空
        obj.num = this.accSub(obj.num, 0.01) // obj.num - 0.01
      } else if (this.type === 'WJWTLX_05') { // 整数型填空
        obj.num = obj.num - 1
      }
      return obj
    },
    accSub(arg1, arg2) {
      var r1, r2, m, n
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      m = Math.pow(10, Math.max(r1, r2))
      // last modify by deeka
      // 动态控制精度长度
      n = (r1 >= r2) ? r1 : r2
      return Number(((arg1 * m - arg2 * m) / m).toFixed(n))
    },
    /*
      * 判断第一个数是否比第二个数大
      * */
    checkBig(n1, n2) {
      return Number(n1) > Number(n2)
    },
    /**
     * 选项改变时触发
     * */
    changeVal(e, t, i) {
      if (e) {
        this.jumpList[i]['value' + t] = ''
        this.jumpList[i]['flag' + t] = 'nolimit'
      } else {
        if (t === 1) {
          this.jumpList[i]['flag' + t] = 'gtr'
        } else {
          this.jumpList[i]['flag' + t] = 'let'
        }
      }
    },

    /*
    * 添加默认配置
    * */
    addJumpList() {
      const obj = {
        type: 'sid',
        flag1: 'gtr',
        flag2: 'let',
        flag1Check: false,
        flag2Check: false,
        value1: '',
        value2: '',
        toid: ''
      }
      this.jumpList.push(obj)
    },
    /*
    * 删除某一项
    * */
    removeJump(i) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.jumpList.splice(i, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
      })
    }

  }
}
</script>

<style lang="scss">
.question-tiankong-jump {
  .box-card{

    margin-bottom: 20px;
    .el-radio{
      margin-right: 10px;
    }
    .el-checkbox{
      margin-right: 0px;
    }
    .el-card__body{
      display: block !important;
      padding: 20px 10px;
    }
  }
  .el-form-item.fixed .el-form-item__content {
    display: flex;
    align-items: center;

    .el-input {
      width: auto;
    }

    .score-tip {
      margin-left: 20px;
      color: red;
    }
  }

  .el-radio-group {
    width: 100%;
  }

  .options .el-form-item__content {
    display: flex;
    align-items: center;

    .el-input {
      width: 100%;
      margin-right: 20px;
    }
  }

  .option-rightasnwer {
    display: inline-block;
    flex-shrink: 0;
    font-size: 14px;
    color: green;
    margin-right: 10px;
  }

  .order-fixed {
    margin: 10px 0;
    padding-left: 100px;
  }

  .remove-option {
    cursor: pointer;
  }

  .add-optiopn {
    margin-left: 100px;
  }

  .tip {
    padding-left: 100px;
    padding-bottom: 10px;
    color: red;

    div {
      margin-top: 10px;
    }
  }
}
</style>
